<template>
  <div>
      <!-- 面包屑区域 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 卡片区域 -->
      <el-card>
          <!-- 消息警告 -->
        <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
          <!-- 步骤条 -->
        <el-steps :space="250" :active="addGoodValue-0" finish-status="success" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

          <!-- 标签页 -->
        <el-form :model="addgoodForm" :rules="addgoodRules" ref="ruleForm" label-width="100px" label-position="top">
            <el-tabs tab-position="left" v-model="addGoodValue" :before-leave="beforeTabLeave" @tab-click="tabClicked">
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="addgoodForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item  label="商品价格" prop="goods_price">
                        <el-input-number v-model="addgoodForm.goods_price" controls-position="right" :min="0" ></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品重量" prop="goods_weight">
                        <el-input-number v-model="addgoodForm.goods_weight" controls-position="right" :min="0" ></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="goods_number">
                        <el-input-number v-model="addgoodForm.goods_number" controls-position="right" :min="0" ></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="goods_cat">
                        <el-cascader :options="CateList" :props="CateProps" v-model="addgoodForm.goods_cat" @change="CateHandChange" clearable></el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-form-item :label="item.attr_name" v-for="(item,index) in manyDataList" :key="index">
                        <el-tag v-for="(itemTag,tagIndex) in item.attr_vals" :key="tagIndex" closable>{{itemTag}}</el-tag>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form-item :label="item.attr_name" v-for="(item,index) in onlyDataList" :key="index">
                        <el-input :value="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                        <!-- 商品图片上传
                        action:指定图片上传api接口
                        :on-preview ： 当点击图片时会触发该事件进行预览操作,处理图片预览
                        :on-remove : 当用户点击图片右上角的X号时触发执行
                        :on-success：当用户点击上传图片并成功上传时触发
                        list-type ：设置预览图片的方式
                        :headers ：设置上传图片的请求头 -->
                    <el-upload
                        :action="uploadURL"
                        list-type="picture"
                        :headers="uploadHeaders"
                        :on-remove="uploadRemove"
                        :on-success="uploadSuccess">
                        <el-button size="small" type="primary">上传图片</el-button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <quill-editor v-model="addgoodForm.goods_introduce"></quill-editor>
                    <el-button type="primary" class="addbtn" @click="addGoodbtn">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
      </el-card>
  </div>
</template>

<script>
export default {
    name: 'addgoods',
    data() {
        return {
            // 保存步骤条激活项索引
            addGoodValue: '0',
            // 商品基本信息表单绑定的信息
            addgoodForm: {
                goods_name: '',
                goods_price: '',
                goods_weight: '',
                goods_number: '',
                goods_cat: [],
                pics: [],
                goods_introduce: '',
                attrs: []
            },
            // 商品基本信息表单校验规则
            addgoodRules: {
                goods_name: [
                      { required: true, message: '请输入商品名称', trigger: 'blur' },
                ],
                goods_price: [
                      { required: true, message: '请输入商品价格', trigger: 'blur' },
                ],
                goods_weight: [
                      { required: true, message: '请输入商品重量', trigger: 'blur' },
                ],
                goods_number: [
                      { required: true, message: '请输入商品数量', trigger: 'blur' },
                ],
                goods_cat: [
                      { required: true, message: '请选择分类', trigger: 'blur' },
                ]
            },
            // 商品基本信息-商品分类的配置设置
            CateProps: {
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            // 获取到的分类数据
            CateList: [],
            // 获取到的商品参数数据
            manyDataList: [],
            // 获取到的商品属性数据
            onlyDataList: [],
            // 上传图片的服务器地址
            uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
            uploadHeaders: { Authorization: window.sessionStorage.getItem('token') }
        }
    },
    created() {
        this.getCateList()
    },
    methods: {
        // 分类数据获取
        async getCateList() {
            const { data: res } = await this.$http.get('categories')
            if (res.meta.status !== 200) { this.$message.error('获取分类数据失败！'); }
            this.CateList = res.data
        },
        // 级联选择器发生变更时触发
        CateHandChange() {
            // 如果用户选择的不是三级分类，则选择无效
            if (this.addgoodForm.goods_cat.length !== 3) {
                this.addgoodForm.goods_cat = []
            }
        },
        // tab标签页切换前触发
        beforeTabLeave(activeName, oldActiveName) {
            if (this.addgoodForm.goods_name.trim() === '') {
                this.$message.error('请输入商品名称!')
                return false
            } else if (this.addgoodForm.goods_price === 0) {
                this.$message.error('请输入商品价格!')
                return false
            } else if (this.addgoodForm.goods_weight === 0) {
                this.$message.error('请输入商品重量!')
                return false
            } else if (this.addgoodForm.goods_number === 0) {
                this.$message.error('请输入商品数量!')
                return false
            } else if (this.addgoodForm.goods_cat.length !== 3) {
                this.$message.error('请选择商品的分类!')
                return false
            }
        },
        // 切换标签页获取参数/属性
        async tabClicked() {
            if (this.addGoodValue === '1') {
                const { data: res } = await this.$http.get(`categories/${this.addgoodForm.goods_cat[2]}/attributes`, { params: { sel: 'many' } })
                if (res.meta.status !== 200) { this.$message.error('获取商品参数失败') }
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
                });
                this.manyDataList = res.data
            } else if (this.addGoodValue === '2') {
                 const { data: res } = await this.$http.get(`categories/${this.addgoodForm.goods_cat[2]}/attributes`, { params: { sel: 'only' } })
                if (res.meta.status !== 200) { this.$message.error('获取商品属性失败') }
                this.onlyDataList = res.data
            }
        },
        // 上传图片删除后触发 file为当前图片的res
        uploadRemove(file) {
            // 获取临时的图片路径
            const fileTemp = file.response.data.tmp_path
            // 用findindex来查询临时路径在pics里面的index是多少
            const fileTempIndex = this.addgoodForm.pics.findIndex(item => item.pic === fileTemp)
            // 通过index来删除pics里面的临时路径
            this.addgoodForm.pics.splice(fileTempIndex, 1)
        },
        // 上传图片成功后触发
        uploadSuccess(res) {
            // 将获取到的tmp_path push到addgoodForm.pics
            this.addgoodForm.pics.push({ pic: res.data.tmp_path })
        },
        // 添加商品功能
        addGoodbtn() {
            // 先对表单项进行校验
            this.$refs.ruleForm.validate(async valid => {
                console.log(this.onlyDataList);
                if (!valid) { this.$message.error('信息校验失败!') }
                // 深拷贝goods_cat
                // 将addForm进行深拷贝，避免goods_cat数组转换字符串之后导致级联选择器报错
                // eslint-disable-next-line no-undef
                const form = _.cloneDeep(this.addgoodForm)
                // 将goods_cat从数组转换为"1,2,3"字符串形式
                form.goods_cat = form.goods_cat.join(',')
                // 处理attrs数组，数组中需要包含商品的动态参数和静态属性
                // 将manyDataList（动态参数）处理添加到attrs
                this.manyDataList.forEach(item => {
                    form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(',') })
                })
                // 将onlyTableData（静态属性）处理添加到attrs
                this.onlyDataList.forEach(item => {
                    form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
                })
                const { data: res } = await this.$http.post('goods', form)
                if (res.meta.status !== 201) {
                    this.$message.error('添加商品失败！')
                }
                this.$message.success('添加商品成功！')
                this.$router.push('/goods')
            })
        }
    }
}
</script>

<style lang="less" scoped>
// 添加商品按钮样式
.addbtn{
    margin-top: 15px;
}

.el-breadcrumb{
    font-size: 14px;
}
</style>
